﻿'   fTray modMain 
'   Copyright (c) 2010 Marvin Westmaas ( MtM / Marvin_The_Martian )
'
'   This program is free software: you can redistribute it and/or modify
'   it under the terms of the GNU General Public License as published by
'   the Free Software Foundation, either version 3 of the License, or
'   (at your option) any later version.
'
'   This program is distributed in the hope that it will be useful,
'   but WITHOUT ANY WARRANTY; without even the implied warranty of
'   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'   GNU General Public License for more details.
'
'   You should have received a copy of the GNU General Public License
'   along with this program.  If not, see <http://www.gnu.org/licenses/>.
Imports System.Runtime.InteropServices
Imports Microsoft.Win32
Imports System.Data.SqlServerCe
Imports System.Data

Module modMAIN
#Region "Declares"
    Dim con As SqlCeConnection
    Dim cmd As SqlCeCommand
    Dim myDA As SqlCeDataAdapter
    Dim myDataSet As DataSet

    Public WithEvents ClientControl As clsClientControl
    Public fLog As New frmLOG
    Public LogWindow As New clsLogwindow
    Public ProjectInfo As clsProjectInfo
    Public MySettings As clsSettings
    Public nIcon As NotifyIcon
    Public _ConfigID As IntPtr
#End Region

#Region "Entry point"

    'Working to get one client coded properly, when done then make changes to enable multiple clients ( arraylist of clsclientcontrol )
    Sub main()
        Dim bTryClose As Boolean = False
        Try
            'set icon to flog.icon
            nIcon = fLog.nIcon
            'check if client is in path
            If ClientPath = "-1" Or ClientPath = "-2" Then
                MsgBox("No client found, application will now exit", vbOKOnly)
                Application.Exit()
            Else
                LogWindow = LogWindow.CreateLog
                LogWindow.EmptyLine()
                LogWindow.WriteLog("fTray version " & My.Application.Info.Version.ToString)
                LogWindow.EmptyLine()
                LogWindow.WriteLog("fTray logging started")
                MySettings = New clsSettings(ClientPath)
                If MySettings.IsEmpty Then
                    'Allow settings change first
                    MySettings.SetDefaults()
                    Dim nSettings As New frmOptions
                    nSettings.cmdCancel.Enabled = False
                    'Will return after save
                    Application.Run(nSettings)
                End If
                'init project info
                ProjectInfo = New clsProjectInfo(ClientPath)
                If ProjectInfo.Projects.IsEmpty Then ProjectInfo.GetProjects(MySettings.MySettings.URLsummary, True)
                'Do Inits
                ClientControl = New clsClientControl(ClientPath, ClientEXE)
                ClientControl.Queue.InitQueue()
                'check run options here!
                Application.EnableVisualStyles()
                fLog.DoInit()
                'Main icon showed, check EOC icon
                If MySettings.MySettings.UseEOC Then
                    ClientControl.EOC.InitEOC()
                    ClientControl.EOC.ShowStatsForm(True)
                End If
                If MySettings.MySettings.StartMinimized Then
                    'should run minimized
                    fLog.WindowState = FormWindowState.Minimized
                    Application.Run(fLog)
                Else
                    fLog.Visible = True
                    Application.Run(fLog)
                End If
                bTryClose = True
            End If
        Catch ex As Exception
            LogWindow.WriteError("Submain", Err)
        Finally
            Try
                If bTryClose Then
                    If ClientControl.ConsoleStatus = clsClientControl.eStatus.active And ClientControl.WindowState = clsClientControl.eWindowState.Hidden Then
                        ClientControl.ShowConsole()
                    End If
                End If
            Catch ex As Exception

            End Try
        End Try
    End Sub
#End Region
#Region "Dll imports"
    <DllImport("kernel32.dll", SetLastError:=True)> _
    Public Function GetConsoleWindow() As IntPtr
    End Function
    <DllImport("kernel32.dll", SetLastError:=True)> _
    Public Function AttachConsole(ByVal procid As Integer) As Boolean
    End Function
    <DllImport("kernel32.dll", SetLastError:=True)> _
    Public Function FreeConsole() As Boolean
    End Function
    <DllImport("user32.dll")> _
    Public Function SetForegroundWindow(ByVal hWnd As IntPtr) As Boolean
    End Function
    <DllImport("user32.dll")> _
    Public Function GetForegroundWindow() As Long
    End Function
    <DllImport("kernel32.dll", SetLastError:=True)> _
    Public Function GenerateConsoleCtrlEvent(ByVal ctrlEvent As Integer, ByVal procid As Integer) As Boolean
    End Function
    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
    Public Function ShowWindow(ByVal hWnd As IntPtr, ByVal nCmdShow As Int32) As Boolean
    End Function
#End Region
#Region "Properties"
#Region ".net version installed"
    Public Enum eDotNetVersion
        Err = 0
        Two = 1
        Three = 2
        ThreePointFive = 3
    End Enum
    Public ReadOnly Property InstalledDOTNETVersion() As eDotNetVersion
        Get
            Try
                Dim rKey As Microsoft.Win32.RegistryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\NET Framework Setup\NDP")
                Dim sName() As String = rKey.GetSubKeyNames
                Dim rDot As eDotNetVersion = eDotNetVersion.Err
                For Each InstVersion As String In sName
                    InstVersion = InstVersion.Replace("v", "")
                    If Mid(InstVersion, 1, 3) = "2.0" And rDot < eDotNetVersion.Two Then
                        rDot = eDotNetVersion.Two
                    ElseIf Mid(InstVersion, 1, 3) = "3.0" And rDot < eDotNetVersion.Three Then
                        rDot = eDotNetVersion.Three
                    ElseIf Mid(InstVersion, 1, 3) = "3.5" And rDot < eDotNetVersion.ThreePointFive Then
                        rDot = eDotNetVersion.ThreePointFive
                    End If
                Next
                Return rDot
            Catch ex As Exception
                Return eDotNetVersion.Err
            End Try
        End Get
    End Property
#End Region
    Public ReadOnly Property ClientPath As String
        Get
            Try
                Dim tPath As String = Application.StartupPath
                If My.Computer.FileSystem.FileExists(tPath & "\Folding@home-Win32-x86.exe") Then
                    Return tPath
                ElseIf My.Computer.FileSystem.FileExists(tPath & "\Folding@home-Win32-GPU.exe") Then
                    Return tPath
                Else
                    Return "-1"
                End If
            Catch ex As Exception
                Return "-2"
            End Try
        End Get
    End Property
    Public ReadOnly Property ClientEXE As String
        Get
            Try
                If My.Computer.FileSystem.FileExists(Application.StartupPath & "\Folding@home-Win32-x86.exe") Then
                    Return Application.StartupPath & "\Folding@home-Win32-x86.exe"
                ElseIf My.Computer.FileSystem.FileExists(Application.StartupPath & "\Folding@home-Win32-GPU.exe") Then
                    Return Application.StartupPath & "\Folding@home-Win32-GPU.exe"
                Else
                    Return vbNullString
                End If
            Catch ex As Exception
                Return vbNullString
            End Try
        End Get
    End Property
    Public ReadOnly Property ClientProcessName As String
        Get
            Try
                Dim tString As String = ClientEXE.Replace(".exe", "")
                Return Mid(tString, tString.LastIndexOf("\") + 2)
            Catch ex As Exception

                Return vbNullString
            End Try
        End Get
    End Property
    Private _dtEOC_Failure As DateTime = DateTime.MinValue
    Private _dtFAHWEB_Failure As DateTime = DateTime.MinValue
    Public Property EOC_Net_Failure() As DateTime
        Get
            Return _dtEOC_Failure
        End Get
        Set(ByVal value As DateTime)
            _dtEOC_Failure = value
        End Set
    End Property
    Public Property FAHWEB_Failure() As DateTime
        Get
            Return _dtFAHWEB_Failure
        End Get
        Set(ByVal value As DateTime)
            _dtFAHWEB_Failure = value
        End Set
    End Property
#End Region
#Region "Constants"
    Public Const SW_HIDE As Integer = 0
    Public Const SW_SHOWNORMAL As Integer = 1
    Public Const SW_SHOWMINIMIZED As Integer = 2
    Public Const SW_SHOWMAXIMIZED As Integer = 3
    Public Const SW_SHOWNOACTIVATE As Integer = 4
    Public Const SW_RESTORE As Integer = 9
    Public Const SW_SHOWDEFAULT As Integer = 10
    Public Const CTRL_C_EVENT As Integer = 0
#End Region

#Region "Functions and subs"
    Public Sub WaitMS(ByVal MS As Long)
        Try
            Dim dEnd As DateTime = DateTime.Now.AddMilliseconds(MS)
            Do While dEnd.Subtract(DateTime.Now).TotalMilliseconds > 0
                Application.DoEvents()
            Loop
        Catch ex As Exception

        End Try
    End Sub

#End Region
End Module
